package service

import (
	"fmt"
	logger "gitee.com/zaper/private-logger"
	"gitee.com/zaper/service-center/constant"
	clientv3 "go.etcd.io/etcd/client/v3"
	"sync"
	"time"
)

var (
	smEtcdMutex sync.Mutex
	clientEtcd  *clientv3.Client
	err         error
)

func GetEtcdClient() (*clientv3.Client, error) {
	smEtcdMutex.Lock()
	defer smEtcdMutex.Unlock()
	etcdEndPoint := []string{
		fmt.Sprintf("http://%s:2379", constant.LocalHost),
		fmt.Sprintf("http://%s:2381", constant.LocalHost),
		fmt.Sprintf("http://%s:2383", constant.LocalHost),
	}

	if clientEtcd != nil {
		return clientEtcd, nil
	}
	clientEtcd, err = clientv3.New(clientv3.Config{
		Endpoints:            etcdEndPoint,
		DialTimeout:          5 * time.Second,
		DialKeepAliveTimeout: 10 * time.Second,
	})

	if err != nil {
		logger.Errorf("New client etcd fail, err is %s", err)
		return nil, err
	}
	return clientEtcd, nil
}
